<template>
  <div class="card-showcase" @mouseenter="isHover = true" @mouseleave="isHover = false">
    <div class="card-showcase__container container-content-middle" ref="cardShowcase">
      <template v-if="vsWidth > 767.98">
        <client-only>
          <Swiper
            ref="swiperRef"
            :modules="modules"
            :centered-slides="true"
            :slides-per-view="2.7"
            :speed="600"
            :loop="true"
            :space-between="-80"
            :breakpoints="breakpoints"
            :pagination="{ el: '.swiper-pagination', clickable: true }"
            :navigation="{ nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev' }"
            class="swiper showcaseSlide swiper--desktop"
            @swiper="onSwiperReady"
          >
            <SwiperSlide
              v-for="card in articleData"
              :key="card.key"
              :data-swiper-key="card.key"
            >
              <div class="slide-content" @click="openArticle(card.key)">
                <div class="img-wrapper">
                  <img
                    v-if="card.poster"
                    class="img-static"
                    :src="card.poster"
                    :alt="card.alt || card.title"
                  />
                  <img
                    v-else
                    class="img-static"
                    :src="card.image || card.meta.image"
                    :alt="card.alt || card.title"
                  />
                </div>
                <div class="slide-content__box bg-white shadow-lg">
                  <h6 class="slide-content__box__title">
                    {{ card.title }}
                  </h6>
                  <div
                    v-if="card.content || card.desc || card.meta.description"
                    class="slide-content__box__content"
                    v-html="card.content || card.desc || card.meta.description"
                  ></div>
                  <h6 v-if="card.subtitle || card.label" class="slide-content__box__subtitle">
                    {{ card.subtitle || card.label }}
                  </h6>
                  <h6 v-else class="slide-content__box__subtitle">
                    {{ getCategoryName(card.category) }}
                  </h6>
                </div>
                <template v-if="card.video_type && card.link">
                  <a
                    v-if="card.video_type === 'outer'"
                    :href="card.link"
                    target="_blank"
                    rel="noopener noreferrer"
                    class="slide-content__play"
                  ></a>
                  <button
                    v-else
                    type="button"
                    class="slide-content__play"
                    @click.stop="openLightbox(card.key)"
                  ></button>
                </template>
              </div>
            </SwiperSlide>
          </Swiper>
          <div class="swiper-footer">
            <div class="swiper-button-prev"></div>
            <div class="swiper-pagination"></div>
            <div class="swiper-button-next"></div>
          </div>
        </client-only>
      </template>
      <template v-else>
        <client-only>
          <Swiper
            ref="swiperRefMobile"
            :modules="modules"
            :centered-slides="true"
            :slides-per-view="1"
            :speed="600"
            :effect="'fade'"
            :fade-effect="{ crossFade: true }"
            :loop="true"
            :pagination="{ el: '.swiper-pagination__mobile', clickable: true }"
            :navigation="{ nextEl: '.swiper-button-next__mobile', prevEl: '.swiper-button-prev__mobile' }"
            class="swiper showcaseSlide swiper--mobile"
            @swiper="onSwiperReady"
          >
            <SwiperSlide
              v-for="card in articleData"
              :key="card.key"
              :data-swiper-key="card.key"
            >
              <div class="slide-content" @click="openArticle(card.key)">
                <div class="img-wrapper">
                  <img
                    v-if="card.poster"
                    class="img-static"
                    :src="card.poster"
                    :alt="card.alt || card.title"
                  />
                  <img
                    v-else
                    class="img-static"
                    :src="card.image || card.meta.image"
                    :alt="card.alt || card.title"
                  />
                </div>
                <div class="slide-content__box bg-white shadow-lg">
                  <h6 class="slide-content__box__title">
                    {{ card.title }}
                  </h6>
                  <div
                    v-if="card.content || card.desc || card.meta.description"
                    class="slide-content__box__content"
                    v-html="card.content || card.desc || card.meta.description"
                  ></div>
                  <h6 v-if="card.subtitle || card.label" class="slide-content__box__subtitle">
                    {{ card.subtitle || card.label }}
                  </h6>
                  <h6 v-else class="slide-content__box__subtitle">
                    {{ getCategoryName(card.category) }}
                  </h6>
                </div>
                <template v-if="card.video_type && card.link">
                  <a
                    v-if="card.video_type === 'outer'"
                    :href="card.link"
                    target="_blank"
                    rel="noopener noreferrer"
                    class="slide-content__play"
                  ></a>
                  <button
                    v-else
                    type="button"
                    class="slide-content__play"
                    @click.stop="openLightbox(card.key)"
                  ></button>
                </template>
              </div>
            </SwiperSlide>
          </Swiper>
          <div class="swiper-footer">
            <div class="swiper-button-prev__mobile swiper-button-prev"></div>
            <div class="swiper-pagination__mobile swiper-pagination"></div>
            <div class="swiper-button-next__mobile swiper-button-next"></div>
          </div>
        </client-only>
      </template>
    </div>

    <Operate v-if="!isPreview" v-model:show="isHover" @handle-edit="showSetting = true" @handle-delete="handleDelete" @handle-copy="handleCopy" @handle-paste="handlePaste"></Operate>
  </div>

  <Setting v-if="!isPreview" v-model:show="showSetting" :data="modelValue"></Setting>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { Swiper, SwiperSlide } from 'swiper/vue'
import { Navigation, Pagination, Autoplay } from 'swiper/modules'
import Operate from '@/common/Operate/index.vue'
import Setting from './setting.vue'
import { randomString } from '@/utils/common'
import { http } from '@/utils/http'
// 导入 Swiper 样式
import 'swiper/css'
import 'swiper/css/navigation'
import 'swiper/css/pagination'

// 定义组件名称
defineOptions({
  name: 'CardShowcase'
})

const props = defineProps({
  modelValue: {
    type: Object,
    default: () => {}
  },

  // 是否预览
  isPreview: {
    type: Boolean,
    default: true
  },

  website: {
    type: String,
    default: 'ywies-tx'
  },

  locale: {
    type: String,
    default: 'sc'
  },

  articleCategories: { // TODO:渲染端传入，文章分类article-categories
    type: Array,
    default: () => [
      {
        "id": 92,
        "key": "school-news",
        "name": "学校新闻",
        "hasArticles": true
      },
      {
        "id": 93,
        "key": "wechat-news",
        "name": "微信精彩文章",
        "hasArticles": true
      },
      {
        "id": 94,
        "key": "press",
        "name": "媒体报导",
        "hasArticles": true
      },
      {
        "id": 95,
        "key": "circulars-n-newsletters",
        "name": "校內刊物",
        "hasArticles": true
      },
      {
        "id": 222,
        "key": "planet-leadership-series-archive",
        "name": "星空说 - Archive",
        "hasArticles": true
      },
      {
        "id": 223,
        "key": "meet-series-archive",
        "name": "“遇见”系列 - Archive",
        "hasArticles": true
      },
      {
        "id": 274,
        "key": "meet-series",
        "name": "“遇见”系列",
        "hasArticles": true
      },
      {
        "id": 275,
        "key": "planet-leadership-series",
        "name": "星空说",
        "hasArticles": true
      },
      {
        "id": 282,
        "key": "ycyw-news",
        "name": "耀中耀华新闻",
        "hasArticles": true
      },
      {
        "id": 290,
        "key": "parent-sharing",
        "name": "家长分享",
        "hasArticles": true
      },
      {
        "id": 291,
        "key": "events",
        "name": "活动预告",
        "hasArticles": true
      },
      {
        "id": 294,
        "key": "ycyw-event",
        "name": "耀中耀华活动",
        "hasArticles": true
      },
      {
        "id": 296,
        "key": "edfutures",
        "name": "未来教育部",
        "hasArticles": true
      },
      {
        "id": 300,
        "key": "yuiuih",
        "name": "测试",
        "hasArticles": true
      }
    ]
  }
})

const emit = defineEmits(['update:modelValue', 'handleDelete', 'handleCopy', 'handlePaste', 'showLightboxVideo', 'showLightboxImage', 'handleClick'])

const handleInit = () => {
  if (props.modelValue && props.modelValue.data) return // 有数据不用初始化
  const data = {
    id: props.modelValue?.id || randomString(),
    type: 'CardShowcase',
    api: props.modelValue?.api || '/component/production/articles',
    getDataType: props.modelValue?.getDataType || 'alumni'
  }
  emit('update:modelValue', data)
} 

const isHover = ref<boolean>(false);
const showSetting = ref<boolean>(false);

const handleDelete = () => {
  emit('handleDelete', props.modelValue.id)
}

const handleCopy = () => {
  emit('handleCopy', props.modelValue)
}

const handlePaste = (type: string) => {
  emit('handlePaste', type)
}

handleInit()

// Swiper 模块
const modules = [Navigation, Pagination, Autoplay]

// Swiper 断点配置
const breakpoints = {
  768: {
    spaceBetween: -100
  },
  1024: {
    spaceBetween: -130
  }
}

const swiperRef = ref<any>(null)
const swiperRefMobile = ref<any>(null)
const cardShowcase = ref<any>(null)
const articleData = ref<any[]>([])
const vsWidth = ref(typeof window !== 'undefined' ? window.innerWidth : 1024)
let mouseTarget: NodeListOf<Element> | null = null
let swiperInstance: any = null

const getData = async () => {
  const url = `${props.modelValue.api}?category=${props.modelValue?.getDataType}&per_page=${5}&page=${1}`;
  const config = {
    headers: {
      website: `${props.website}-${props.locale}`,
    },
  };
  let data = await http.get(url, config);
  articleData.value = data.data.data;
}

// 获取 Swiper 实例
const onSwiperReady = (swiper: any) => {
  swiperInstance = swiper
  handleSwiperReadied()
}

// 打开文章
const openArticle = (key: string) => {
  if (typeof window !== 'undefined') {
    window.scroll({ top: 0, left: 0, behavior: 'smooth' })
  }
  emit('handleClick', `/article/${props.modelValue?.getDataType}/${key}`)
}

// 获取分类名称
const getCategoryName = (v: string) => {
  return props.articleCategories.filter((i: any)=> i['key'] === v)[0].name
}

// 打开灯箱
const openLightbox = (key: string) => {
  const modalList = articleData.value.filter((item: any) => item.video_type !== "outer");
  const modalIdx = modalList.findIndex((item: any) => item.key == key);
  emit('showLightboxVideo', {
    idx: modalIdx,
    list: modalList,
  })
}

// 鼠标悬停处理
const onHover = (e: any) => {
  if (!swiperInstance) return
  const classList = e.path?.[0]?.className?.split(' ') || []
  if (classList.includes('swiper-slide-next')) {
    swiperInstance.slideNext()
  } else if (classList.includes('swiper-slide-prev')) {
    swiperInstance.slidePrev()
  }
}

// 处理 Swiper 就绪
const handleSwiperReadied = () => {
  if (typeof document === 'undefined') return
  mouseTarget = document.querySelectorAll('.swiper-slide')
  mouseTarget?.forEach((el) => {
    el.addEventListener('mouseenter', onHover)
  })
}

// 监听窗口大小变化
const handleResize = () => {
  if (typeof window !== 'undefined') {
    vsWidth.value = window.innerWidth
  }
}

// 生命周期
onMounted(() => {
  getData()
  if (typeof window !== 'undefined') {
    window.addEventListener('resize', handleResize)
  }
  nextTick(() => {
    if (props.modelValue?.getBackendData && swiperInstance) {
      setTimeout(() => {
        swiperInstance.slideTo(3)
      }, 300)
    }
  })
})

onUnmounted(() => {
  if (typeof window !== 'undefined') {
    window.removeEventListener('resize', handleResize)
  }
  mouseTarget?.forEach((el) => {
    el.removeEventListener('mouseenter', onHover)
  })
})
</script>

<style lang="scss" scoped>
.card-showcase {
  position: relative;
}

.bg-white {
  --bs-bg-opacity: 1;
  background-color: rgba(255,255,255,var(--bs-bg-opacity))!important;
}

.shadow-lg {
  box-shadow: 0 8px 32px 0 rgba(130,130,140,.24)!important
}

.card-showcase__container {
  position: relative;

  @media (max-width: 767.98px) {
    padding-left: 0;
    padding-right: 0;
  }
}

.swiper-footer {
  position: absolute;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  left: 0;
  margin-top: 32px;
}

.swiper-pagination {
  position: relative;
  bottom: 1px;
  display: flex;
  align-items: center;
}

.swiper-pagination :deep(.swiper-pagination-bullet) {
  margin: 0 6px;
}

.swiper-button-prev,
.swiper-button-next {
  position: relative;
  left: 0;
  right: 0;
  margin-top: 0;
  width: 24px;
  height: 24px;
  background-image: url('~static/images/icons/icon-slides-arrow--dark.svg');
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
  cursor: pointer;
}

.swiper-button-prev::after,
.swiper-button-next::after {
  content: '';
}

.swiper-button-prev {
  transform: scale(-1);
}

.img-wrapper {
  position: relative;
  width: 100%;
}

.img-wrapper img {
  position: absolute;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.swiper-slide {
  width: 300px;
  height: 360px;
  opacity: 0.6;
  transform: scale(0.72);
  transition: all 0.4s ease-in-out;
}

.swiper-slide .slide-content {
  width: 100%;
  height: 100%;
  opacity: 0;
  transition: opacity 0.3s;
  position: relative;
  cursor: pointer;
}

.swiper-slide .slide-content .img-wrapper {
  border-radius: 8px;
  height: 100%;
  overflow: hidden;
}

@media (max-width: 767.98px) {
  .swiper-slide .slide-content .img-wrapper {
    border-radius: 0;
  }
}

.swiper-slide-active {
  z-index: 1;
  opacity: 1;
  box-shadow: 0px 8px 32px rgba(130, 130, 140, 0.24);
  transform: scale(0.9) perspective(200px) translate3d(0, 0, 20px);
}

.swiper-slide-active .slide-content {
  opacity: 1;
}

.swiper-slide-next {
  box-shadow: 0px 5.77778px 23.1111px rgba(130, 130, 140, 0.24);
  transform: scale(0.72) perspective(200px) translate3d(0px, 0, 0px);
}

.swiper-slide-next .slide-content {
  opacity: 1;
}

.swiper-slide-prev {
  box-shadow: 0px 5.77778px 23.1111px rgba(130, 130, 140, 0.24);
  transform: scale(0.72) perspective(200px) translate3d(0px, 0, 0px);
}

.swiper-slide-prev .slide-content {
  opacity: 1;
}

.swiper-pagination {
  bottom: 0;
}

:deep(.slide-content__box) {
  position: absolute;
  width: 196px;
  left: -4px;
  top: 50%;
  transform: translateY(-50%);
  padding: 24px 12px 22px;
  border-radius: 0 8px 8px 0;
}

.slide-content__box__title {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  color: #003d99;
  margin-bottom: 29px;
  font-weight: 600;
  font-size: 16px;
  line-height: 1.5;
}

.slide-content__box__content {
  display: -webkit-box;
  -webkit-line-clamp: 7;
  line-clamp: 7;
  -webkit-box-orient: vertical;
  overflow: hidden;
  margin-bottom: 29px;
  line-height: 1.3;
  font-size: 14px;
  color: #1a1a1a;
}

.slide-content__box__content > * {
  font-size: 14px;
  color: #1a1a1a;
  line-height: 1.3;
}

.slide-content__box__subtitle {
  font-size: 14px;
  color: #0032a0;
  font-weight: 500;
}

:deep(.slide-content__play) {
  padding: 0;
  position: absolute;
  right: 24px;
  bottom: 24px;
  width: 60px;
  height: 60px;
  background: none;
  border: none;
  background-image: url('~static/images/icons/icon-video-play-btn.svg');
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
  z-index: 1;
  cursor: pointer;
}

:deep(.slide-content__play:hover) {
  background-image: url('~static/images/icons/icon-video-play-btn--hover.svg');
}

@media (max-width: 767.98px) {
  :deep(.slide-content__play) {
    right: 13px;
    bottom: 14px;
  }
}
</style>
